<?php
class info extends adminController {
    public $_index = 'admin/info/index';
    public $_listView = 'admin/info/list';
    public $_addView = 'admin/info/add';
    public $_editView = 'admin/info/edit';
    
	public function __construct() {
		parent::__construct ();
        $this->session->set_userdata('selectedMenuAdmin', 'info');
	}
	
    public function loadView($temp) {
        if (!isset($temp['data']))
            $temp['data'] = '';
        $this->load->view('admin/template', $temp);
    }
    
    public function index() {
        $this->_data['template'] = $this->_listView;
        $this->_data['data'] = $this->infoModel->get_by(array('languageCode' => $this->session->userdata('languageCode')));
        $this->loadView($this->_data);
    }
    
    public function add() {
        $this->_data['template'] = $this->_addView;
        $languages = $this->languageModel->get();
        if(!$this->isPost()) {
            $this->loadView($this->_data);
            return;
        }
        $data = $this->input->post();
        
        $infoId = $this->infoModel->getMax('infoId');
        $infoId = $infoId['infoId'] ? $infoId['infoId'] +1 : 1;
        
        $slug = mb_strtolower(url_title(removesign($data['title'])));
        if($this->infoModel->check_exist('slug', $slug)) {
            $slug = $slug.'-'.random_string('alnum', 4);
        }
        $data['slug'] = $slug;
        $data['infoId'] = $infoId;
        $this->infoModel->insert($data);
        
        $ori_lang = $data['languageCode'];
        
        foreach($languages as $key => $value) {
            if($value['languageCode'] == $ori_lang) continue;
            $data['languageCode'] = $value['languageCode'];
            $this->infoModel->insert($data);
        }
        
        redirect(base_url().$this->_index);
    }
    
    public function edit($id) {
        $this->_data['template'] = $this->_editView;
        if(!$this->isPost()) {
            $this->_data['data'] = $this->infoModel->read($id);
            $this->loadView($this->_data);
            return;   
        }
        $this->infoModel->update($this->input->post(), array('id' => $id));
        redirect(base_url().$this->_index);
    }
    
    public function editLanguage($infoId, $languageCode) {
        $info = $this->infoModel->read(array('infoId' => $infoId, 'languageCode' => $languageCode));
        redirect(base_url().$this->_editView.'/'.$info['id']);
    }
    
    public function delete($infoId) {
        $this->infoModel->deleteBy('infoId', $infoId);
        redirect(base_url().$this->_index);
    }
}
?>